# -*- coding: utf-8 -*-
# @Time    : 2024/9/27 17:13
# @Author  : Alvin
# @File    : SyncOrderUpdateTask.py
# @Des     :
import logging
import logging.handlers
import logging.handlers
import multiprocessing
import os
import time
from functools import partial
from typing import List, Dict

from handler.SyncOrderUpdateImpl import SyncOrderUpdateImpl
from utils import CommonUtil
from utils.DatabaseHandler import DatabaseHandler


def init_logging():
    """
    日志文件设置
    """
    if not os.path.exists("log"):
        os.makedirs("log")
    logger = logging.getLogger()
    logger.setLevel(20)

    sh = logging.StreamHandler()
    current_path = os.path.dirname(__file__)
    log_file = f"{current_path}/log/update_task.log"
    file_log = logging.handlers.TimedRotatingFileHandler(log_file, 'MIDNIGHT', 1, 15)
    formatter = logging.Formatter('[%(asctime)s] [%(levelname)-7s] [%(module)s:%(filename)s-%(funcName)s-%(lineno)d] %(message)s')
    sh.setFormatter(formatter)
    file_log.setFormatter(formatter)

    logger.addHandler(sh)
    logger.addHandler(file_log)

    logging.info("Current log level is : %s", logging.getLevelName(logger.getEffectiveLevel()))


class SyncOrderUpdateTask:

    def __init__(self):
        self.chunk_size = 1000
        self.max_workers = 9
        self.log_text = "同步单更新任务"

    def excute_sync_order_update(self):
        logging.info(f"----------------------------------------{self.log_text} start---------------------------------------")
        logging.info(f"【{self.log_text}】开始时间:%s", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        dbDataList = DatabaseHandler().get_sync_order_update_list()
        if dbDataList is None or len(dbDataList) <= 0:
            logging.info(f"{self.log_text}任务数量为0，任务结束")
            return
        all_data_list = CommonUtil.splitList(dbDataList, self.chunk_size)
        logging.info(f"{self.log_text}数据库查询结束,共获取 {len(dbDataList)} 条数据，划分为 {len(all_data_list)} 个分块")

        for index, data_list in enumerate(all_data_list):
            batch_index = index + 1
            logging.info(f"开始第：{batch_index}/{len(all_data_list)}次任务")
            impl = SyncOrderUpdateImpl()
            impl.start_handle_dy_update_task(batch_index, data_list)

        logging.info(f"【{self.log_text}】任务结束时间:%s", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        logging.info(f"----------------------------------------{self.log_text} all end---------------------------------------")


if __name__ == '__main__':
    init_logging()
    syncOrderUpdateTask = SyncOrderUpdateTask()
    syncOrderUpdateTask.excute_sync_order_update()
